#!/usr/bin/env python
# $Id: htmlcreate.py aa130fbc3a83 2012/12/28 04:41:10 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# File htmlcreate.py generated on Sunday December 23, 2012 @01:58:11 PST
#
__version__  = "$Revision: aa130fbc3a83 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-12-28 04:41:10Z $"

import os
import optparse
import sys

from pyparsing import Suppress, quotedString, removeQuotes, Literal, LineEnd
from pyparsing import Group, Keyword, pythonStyleComment, ParseFatalException
from pyparsing import ParseException, OneOrMore

from venya.lib import exception, cmdparser, stdlib

class HTMLConfigParse(object):
   def __init__(self, FileName):
      if os.path.exists(FileName):
         self._file = FileName
      else:
         self.error("%s file is not found", FileName)

      self._lb, self._rb = map(Suppress, "{}")
      self._quoted = quotedString.copy().setParseAction(removeQuotes)

   def error(self, fmt, *args):
      errmesg = None
      if len(args):
         errmesg = stdlib.sprintf(fmt, *args)
      else:
         errmesg = str(fmt)

      raise ValueError(errmesg)

   def __str__(self):
      return stdlib.my_str(self._file)

   @property
   def rule(self):
      equal = Literal("=").suppress()
      directory = Group(Keyword("directory") + equal + self._quoted)
      htmlfile = Group(Keyword("htmlfile") + equal + self._quoted)
      template = Group(Keyword("template") + equal + self._quoted)
      pdffiles = Group(Keyword("files") + self._lb + OneOrMore(
         self._quoted + equal + self._quoted).setParseAction(
            self.test) + self._rb)

      rule = directory + htmlfile + template + pdffiles
      rule.ignore(Literal("\\") + LineEnd())
      rule.ignore(pythonStyleComment)

      return rule

   def parse(self):
      try:
         with open(self._file, "r") as fh:
            results = self.rule.parseString(fh.read())
      except ParseFatalException as err:
         self.error("parsing failed on %s: %s", self._file, err)
      except ParseException as err:
         self.error("syntax error on line %d col %d in file %s",
               err.lineno, err.col, self._file)

      return results

class create(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-t", "--template", type = "str",
            help = "Template file to use for generating html",
            default = "html.tmpl", dest = "template"),
         optparse.make_option("-c", "--config", type = "str",
            help = "Config file to use to generate html",
            default = "html.cfg", dest = "config"),
   ) + cmdparser.GetOpt.option_list

   usage = "[ options ]"
   help = """

   More to come
   """

   def __init__(self, **kwargs):
      super(create, self).__init__(**kwargs)

   @cmdparser.getopts
   def handle(self):
      print(self.options, self.arguments)
      if self.options.config:
         parser = HTMLConfigParse(self.options.config)
         results = parser.parse()
         directory = results[0][1]
         htmlfile = results[1][1]
         template = results[2][1]
         print(results)

if __name__ == "__main__":
   crt = None
   try:
      crt = create(version = 1.0, args = sys.argv)
      if len(crt) <= 1:
         crt.printhelp()
      else:
         crt.handle()
   except exception.GetOptError as err:
      print(err)
      sys.exit(1)



